package cn.yangliu.comm.tools;

import com.alibaba.fastjson.JSON;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 用这个类必须在web.xml中配置
 * <p>
 * <listener>
 * <listener-class>
 * org.springframework.web.context.request.RequestContextListener
 * </listener-class>
 * </listener>
 */
public final class WebUtils {
    public static final HttpSession getSession() {
       HttpSession session = getRequest().getSession();
        return session;
    }

    public static final <T> T getAttributeFromRequest(String name) {
        HttpServletRequest request = getRequest();
        Object object = request.getAttribute(name);
        @SuppressWarnings("unchecked")
        T t = (T) object;
        return t;
    }

    public static final void setAttribute4Request(String name, Object value) {
        HttpServletRequest request = getRequest();
        request.setAttribute(name, value);
    }

    public static final void setAttribute4Session(String name, Object value) {
        HttpSession session = getSession();
        session.setAttribute(name, value);
    }

    public static  final <T> T getAttributeFromSession(Class<T> clazz, String name) {
        HttpSession session = getSession();
        Object object = session.getAttribute(name);
        T t = (T) object;
        return t;
    }
    public static final <T> T getAttributeFromSession(String name) {
        HttpSession session = getSession();
        Object object = session.getAttribute(name);
        T t = (T) object;
        return t;
    }

    public static final HttpServletRequest getRequest() {
        ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        HttpServletRequest request = attr.getRequest();
        return request;
    }

    public static final HttpServletResponse getResponse() {
        ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        HttpServletResponse response = attr.getResponse();
        return response;
    }

    public static final String getRequestParams() {
        String paramString = "";
        //获取参数map
        Map<String, String[]> params = getRequest().getParameterMap();
        if (params == null) {
            return paramString;
        }
        //获取全部参数名
        Set<String> paramNames = params.keySet();
        int index = 0;
        //遍历参数名
        for (String paramName : paramNames) {
            index++;
            paramString += paramName + "=[";
            String[] values = params.get(paramName);
            //values = hideValues(paramName, values);
            if (values.length == 1) {
                if (index == paramNames.size()) {
                    paramString += values[0] + "]";
                    continue;
                }
                paramString += values[0] + "],";
                continue;
            }

            for (int i = 0; i < values.length; i++) {
                if (i < values.length - 1) {
                    paramString += values[i] + ",";
                    continue;
                }
                if (index == paramNames.size()) {
                    paramString += values[i] + "]";
                    continue;
                }
                paramString += values[i] + "],";
            }
        }
        return paramString;
    }

    public static final String getFullUrl(){
        HttpServletRequest request = getRequest();
        
        Map<String,String[]> paramsMap = request.getParameterMap();
        
        Set<String> set = paramsMap.keySet();
        StringBuilder sb = new StringBuilder(request.getRequestURI()).append("?");
        for (String paramName : set) {
            String [] values = paramsMap.get(paramName);
            for (String value : values) {
                sb.append(paramName).append("=").append(value).append("&");
            }
        }
        return sb.toString();
    }


    private static final List<String> paramNames = Arrays.asList("password", "pwd", "pass","oldPass","oldpass","oldPassword","oldpassword","newPass","newPassword","newpass","newpassword");

    private static final String[] hideValues(String paramName, String[] values) {
        if (paramNames.contains(paramName)) {
            for (int i = 0; i < values.length; i++) {
                String value = CryptUtils.generateDigestWithMD5(values[i]);
                value = StringUtils.hide(value, 0, 0);
                values[i] = value;
            }
        }
        if ("photo".equals(paramName)){
            values[0]="picture";
        }
        return values;
    }

    public static final String getIp() {
        HttpServletRequest request =getRequest();
        String ip = request.getHeader("x-forwarded-for");
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    public static final boolean checkJsonAjax(){
        HttpServletRequest request = getRequest();
        String header = request.getHeader("x-requested-with");

        if (StringUtils.isNotEmpty(header) && header.equalsIgnoreCase("XMLHttpRequest")){ //如果是ajax请求响应头会有x-requested-with
            return true;
        }

        String contentType = request.getContentType();

        if (StringUtils.isNotEmpty(contentType)){
            contentType = contentType.toLowerCase();
            if (contentType.contains("application/json")){
                return true;
            }
        }
        return false;
    }

    public static void printData(Object data, HttpServletResponse response) {
        PrintWriter pw = null;
        try {
            pw = response.getWriter();
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            String content = JSON.toJSONString(data);
            pw.println(content);
            pw.flush();
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        } finally {
            IOUtils.close(pw);
        }

    }
}